'use strict'

const { Book, Op } = require('../model');
const { at } = require('lodash');

let fn_index = async (ctx, next) => {
    ctx.body = 'hello word';
}

let fn_list = async (ctx, next) => {
    let keyword = ctx.request.query.keyword || '';
    if (keyword === '') {
        let list =await Book.findAll({
            order: ['id']
        });
        ctx.body = list;
    } else {
        let list =await Book.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? -1 : parseInt(keyword) },
                    { name: { [Op.like]: `%${keyword}%` } },
                    { price: isNaN(keyword) ? -1 : parseFloat(keyword) },
                    { press: { [Op.like]: `%${keyword}%` } }
                ],
                order: ['id']
            }
        })
        ctx.body = list;
    }
}

let fn_list_id = async (ctx, next) => {
    let id = ctx.request.params.id;
    let data =await Book.findByPk(id)
    if (data) {
        ctx.body = {
            code: 1000,
            data: data,
            msg: '获取成功'
        };
    } else {
        ctx.body = {
            code: 400,
            data: null,
            msg: '获取失败，没有找到'
        };
    }
}
let fn_post = async (ctx, next) => {
    let obj = ctx.request.body
    let tmpObj = {
        name: obj.name,
        price: isNaN(obj.price) ? -1 : parseFloat(obj.price),
        press: obj.press
    }
    await Book.create(tmpObj);
    ctx.body ={
        code: 1000,
        data: tmpObj,
        msg: '新增成功'
    };
}
let fn_put = async (ctx, next) => {
    let id=ctx.request.params.id;
    let obj=ctx.request.body;
    let book=await Book.findByPk(id)
    if (book) {
        await Book.update(obj,{
            where:{
                id:id
            }
        });
        ctx.body={
            code:1000,
            data:book,
            msg:'修改成功。'
        }
    }else{
        ctx.body={
            code:400,
            data:null,
            msg:'指定修改的记录或者元素不存在，请确认后重试'
        }
    }
}

let fn_delete = async (ctx, next) => {
    let id=ctx.request.params.id
    console.log(id);
    let book=await Book.findByPk(id);
    if (book) {
        await Book.destroy({
            where:{
                id:id
            }
        })
        ctx.body={
            code:1000,
            data:id,
            msg:'删除成功'
        }
    }else{
        ctx.body = {
            code: 400,
            data: '',
            msg: '你指定删除的记录不存在，请确认后重试'
        }
    }
}


module.exports = {
    'get /': fn_index,
    'get /books': fn_list,
    'get /books/:id': fn_list_id,
    'post /books': fn_post,
    'put /books/:id': fn_put,
    'delete /books/:id': fn_delete
}